/*
    Copyright 2009 Spencer B. Koehler, Ph.D.

    This file is part of the Brillig Toolkit.

    The Brillig Toolkit is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    The Brillig Toolkit is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with The Brillig Toolkit.  If not, see <http://www.gnu.org/licenses/>.
*/
package org.brillig.match.osobdb;


import java.util.LinkedHashMap;
import java.util.Map;

/**
 * An LRU cache for osob blocks.
 * <p>
 * @author Spence Koehler
 */
class OsobBlockCache {

  private static final boolean UNLIMITED_CACHE_SIZE = true;


  private Map<Integer, OsobBlock> blockCache;

  OsobBlockCache(int cacheSize) {
    this.blockCache = new LRU<Integer, OsobBlock>(UNLIMITED_CACHE_SIZE ? 1000 : cacheSize);
  }

  public OsobBlock getBlock(int blockId) {
    return blockCache.get(blockId);
  }

  public void putBlock(int blockId, OsobBlock block) {
    this.blockCache.put(blockId, block);
  }
  
  static class LRU<K, V> extends LinkedHashMap<K, V> {

    private static final long serialVersionUID = 42L;

    private int cacheSize;

    LRU(int cacheSize) {
      super(cacheSize, 0.75F, true);
      this.cacheSize = cacheSize;
    }

    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
      boolean result = size() > this.cacheSize;
      if (result) {
        eldest.setValue(null);
      }
      return result;
    }
  }
}
